package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private static final ExecutorService CACHE_EXECUTOR = Executors.newFixedThreadPool(10);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {

        //解决缓存穿透
      //  Shop shop = cacheClient.queryWhthPassThrouth(CACHE_SHOP_KEY,id,Shop.class,id2->getById(id),CACHE_SHOP_TTL,TimeUnit.MINUTES);

        //互斥锁解决缓存击穿
      //  Shop shop = queryWithMutex(id);

        //逻辑过期解决缓存击穿
        Shop shop = cacheClient.queryWithMutex(CACHE_SHOP_KEY,id,Shop.class,id2->getById(id),CACHE_SHOP_TTL,TimeUnit.MINUTES);
        return Result.ok(shop);
    }
    private Shop qurtyWhthPassThrouth(Long id){
        //redis 查询
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);

            return shop;
        }
        if(shopJson != null){
            return null;
        }
        Shop shop;
        //查询数据库
        shop = getById(id);
        //不存在
        if (shop == null) {
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);

            return null;
        }
        //存在,写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shop;
    }
//    private Shop queryWithMutex(Long id){
//        while (true) {
//            //redis 查询
//            String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//            if (StrUtil.isNotBlank(shopJson)) {
//                Shop shop = JSONUtil.toBean(shopJson, Shop.class);
//
//                return shop;
//            }
//            if(shopJson != null){
//                return null;
//            }
//            //缓存没有命中获取锁
//            String lockKey = LOCK_SHOP_KEY + id;
//            boolean result = tryLock(lockKey);
//            if(!result){
//                try {
//                    Thread.sleep(50);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//                continue;
//            }
//            Shop shop;
//            try {
//                //查询数据库
//                shop = getById(id);
//                //不存在
//                if (shop == null) {
//                    stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
//
//                    return null;
//                }
//                //存在,写入redis
//                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//
//            } finally {
//                //释放互斥锁
//                unlock(lockKey);
//            }
//
//            return shop;
//        }
//    }
//    public Shop queryWithLogicalEmpire(Long id){
//
//            //redis 查询
//            String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//            if (StrUtil.isBlank(shopJson)) {
//                return null;
//            }
//            RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
//            Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
//            LocalDateTime expireTime = redisData.getExpireTime();
//            LocalDateTime now = LocalDateTime.now();
//            if(expireTime.isAfter(now)){
//                return shop;
//            }
//            //过期了
//            String lockKey = LOCK_SHOP_KEY + id;
//            boolean result = tryLock(lockKey);
//            if(!result){
//                return (Shop) redisData.getData();
//            }
//            CACHE_EXECUTOR.submit(() -> {
//                try {
//                    //  二次检查：防止其他线程已经更新缓存
//                    String json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
//                    RedisData newData = JSONUtil.toBean(json, RedisData.class);
//                    if (newData.getExpireTime().isAfter(LocalDateTime.now())) {
//                        // 已经被其他线程更新了，无需重复构建
//                        return;
//                    }
//                    //写入redis
//                   // stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL, TimeUnit.MINUTES);
//                    saveShop2Redis(id,50L);
//
//                } finally {
//                    //释放互斥锁
//                    unlock(lockKey);
//                }
//            });
//
//
//            return shop;
//
//    }

    @Override
    public Result update(Shop shop) {

        Long id = shop.getId();
        if(id == null) {
            return Result.fail("店铺id不能为空");
        }

        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());

        return Result.ok();
    }


    private void saveShop2Redis(Long id,Long expireSeconds){

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Shop shop = getById(id);
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY+id,JSONUtil.toJsonStr(redisData));


    }
}
